﻿using System;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Linq;

namespace Model
{
    public class ModelBase : INotifyPropertyChanged, INotifyPropertyChanging
    {

        #region INotifyPropertyChanging Members

        public event PropertyChangingEventHandler PropertyChanging;

        protected void NotifyPropertyChanging(string name)
        {
            var pci = PropertyChanging;
            if (pci != null)
            {
                pci(this, new PropertyChangingEventArgs(name));
            }
        }

        #endregion

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        protected void NotifyPropertyChanged(string name)
        {
            var pc = PropertyChanged;
            if (pc != null)
            {
                pc(this, new PropertyChangedEventArgs(name));
            }
        }

        #endregion

    }

    public interface ILastUpdate
    {
        DateTime LastUpdate { set; }
    }


    public static class ModelHelper
    {
        public static void Add<T>(this T it) where T : ModelBase, ILastUpdate
        {
            var db = DBDataContext.Default;
            it.LastUpdate = DateTime.Now;
            db.GetTable<T>().InsertOnSubmit(it);
            db.SubmitChanges();
        }

        public static void Update<T>(this T it) where T : ModelBase, ILastUpdate
        {
            var db = DBDataContext.Default;
            it.LastUpdate = DateTime.Now;
            db.SubmitChanges();
        }
        public static void Delete<T>(this T it) where T : ModelBase
        {
            var db = DBDataContext.Default;
            db.GetTable<T>().DeleteOnSubmit(it);
            db.SubmitChanges();
        }
        public static void DeleteOldProjects()
        {
            var db = DBDataContext.Default;
            var count = db.TowPointProjet.Count();
            if (count > 10)
            {
                var cntToDel = count - 10;
                var toDel = db.TowPointProjet.OrderBy(i => i.LastUpdate).Take(cntToDel).ToList();
                db.TowPointProjet.DeleteAllOnSubmit(toDel);
                db.SubmitChanges();
            }
        }
    }
}
